package com.jnu.supermaket;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.supermaket.data.DataBank;
import com.jnu.supermaket.data.ShopItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    public static final int RESULT_CODE_ADD_DATA = 996;
    private List<ShopItem> shopItems;
    private MyRecyclerViewAdapter recyclerViewAdapter;
    public static final int REQUEST_CODE_ADD = 123;
    public static final int REQUEST_CODE_EDIT = 124;
    private DataBank dataBank;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ADD) {
            if (resultCode == RESULT_CODE_ADD_DATA) {
                String name = data.getStringExtra("name");
                Double price = data.getDoubleExtra("price", 0);
                int position=data.getIntExtra("position",shopItems.size());
                shopItems.add(position,new ShopItem(name, R.drawable.a1, price));
                dataBank.saveData();
                recyclerViewAdapter.notifyItemInserted(position);
            }
        }
        if (requestCode == REQUEST_CODE_EDIT) {
            if (resultCode == RESULT_CODE_ADD_DATA) {
                String name = data.getStringExtra("name");
                Double price = data.getDoubleExtra("price", 0);
                int position = data.getIntExtra("position", shopItems.size());
                shopItems.get(position).setName(name);
                shopItems.get(position).setPrice(price);
                dataBank.saveData();
                recyclerViewAdapter.notifyItemChanged(position);
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();

        FloatingActionButton fabAdd=findViewById(R.id.floating_action_button_add);
        fabAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,InputActivity.class);
                intent.putExtra("position",shopItems.size());
                MainActivity.this.startActivityForResult(intent, REQUEST_CODE_ADD);
            }
        });

        RecyclerView mainRecycleView = findViewById(R.id.recycle_view_items);
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        mainRecycleView.setLayoutManager(layoutManager);//设置布局管理器

        //设置Adapter
       recyclerViewAdapter=new MyRecyclerViewAdapter(shopItems);
        mainRecycleView.setAdapter(recyclerViewAdapter);

    }

    public void initData() {
        dataBank = new DataBank(MainActivity.this);
        shopItems= dataBank.loadData();
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter {
        private List<ShopItem> shopItems;

        public MyRecyclerViewAdapter(List<ShopItem> shopItems) {
            this.shopItems=shopItems;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.shop_item_holder, parent, false);
//在应用中自定义一个view，需要获取这个view的布局，需要用到
//(LinearLayout) LayoutInflater.from(context).inflate(R.layout.contentitem, null);
//这个方法。
            return new MyViewHolder(view);
        }
        //这个方法主要生成为每个Item inflater出一个View，但是该方法返回的是一个ViewHolder。该方法把View直接封装在ViewHolder中，然后我们面向的是ViewHolder这个实例，当然这个ViewHolder需要我们自己去编写。
        //在实际开发中LayoutInflater这个类还是非常有用的，它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件，并且实例化；而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。 具体作用： 1、对于一个没有被载入或者想要动态载入的界面，都需要使用LayoutInflater.inflate()来载入；
        //
        //2、对于一个已经载入的界面，就可以使用Activiyt.findViewById()方法来获得其中的界面元素。



        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            MyViewHolder holder=(MyViewHolder)Holder;
            holder.getImageView().setImageResource(shopItems.get(position).getPictureID());
            holder.getTextViewName().setText(shopItems.get(position).getName());
            holder.getTextViewPrice().setText(shopItems.get(position).getPrice()+" ");
//这个方法主要用于适配渲染数据到View中。方法提供给你了一viewHolder而不是原来的convertView。

        }

        @Override
        public int getItemCount() {
            return shopItems.size();
            //这个方法就类似于BaseAdapter的getCount方法了，即总共有多少个条目。
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener,MenuItem.OnMenuItemClickListener{

            private final ImageView imageView;
            private final TextView textViewName;
            private final TextView textViewPrice;



            public MyViewHolder(@NonNull View itemView) {
                super(itemView);//编译器会自动在子类构造函数的第一句加上 super(); 来调用父类的无参构造器；此时可以省略不写。如果想写上的话必须在子类构造函数的第一句，可以通过super来调用父类其他重载的构造方法，只要相应的把参数传过去就好。
                this.imageView= itemView.findViewById(R.id.image_view_shop_item);
                this.textViewName=itemView.findViewById(R.id.text_view_shop_item_name);
                this.textViewPrice=itemView.findViewById(R.id.text_view_shop_item_price);

                itemView.setOnCreateContextMenuListener(this);//从RecyclerView的Adapter入手，在Adapter的ViewHolder中为每个itemView设置setOnLongClickListener监听，然后在长按监听回调中设置当前的position，为每个itemView设置setOnCreateContextMenuListener监听，通过上面记录的position来执行相应的动作。

            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewPrice() {
                return textViewPrice;
            }
            @Override
            public void onCreateContextMenu (ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {// ViewHolder 中 实现 OnCreateContextMenuListener 接口
                int position = getAdapterPosition();//从onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)方法传递进来的menuInfo中获取到相应的position信息。
                MenuItem star = contextMenu.add(Menu.NONE, 1, 1, "Add" + position);
                MenuItem edit = contextMenu.add(Menu.NONE, 2, 2, "Edit" + position);
                MenuItem delete = contextMenu.add(Menu.NONE, 3, 3, "Delete" + position);

                star.setOnMenuItemClickListener((MenuItem.OnMenuItemClickListener) this);
                edit.setOnMenuItemClickListener((MenuItem.OnMenuItemClickListener) this);
                delete.setOnMenuItemClickListener((MenuItem.OnMenuItemClickListener) this);

            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                 final int position=getAdapterPosition();
                 Intent intent;
                switch(menuItem.getItemId()){
                    case 1:
                        /*final View dialogueView=LayoutInflater.from(MainActivity.this).inflate(R.layout.dialogue_input_item,null);
                        final AlertDialog.Builder alterDialogBuilder=new AlertDialog.Builder(MainActivity.this);
                        alterDialogBuilder.setView(dialogueView);
                        alterDialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                EditText editName= dialogueView.findViewById(R.id.edit_text_name);
                                EditText editPrice= dialogueView.findViewById(R.id.edit_text_price);
                                shopItems.add(position,new ShopItem(editName.getText().toString(),R.drawable.a2,Double.parseDouble(editPrice.getText().toString())));
                                MyRecyclerViewAdapter.this.notifyItemInserted(position);
                            }
                        });
                        alterDialogBuilder.setCancelable(false).setNegativeButton("取消", new DialogInterface.OnClickListener(){//点否
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {


                            }
                        });
                        alterDialogBuilder.show();
                        shopItems.add(position,new ShopItem("萝卜",R.drawable.a2,111.6));
                        MyRecyclerViewAdapter.this.notifyItemInserted(position);
                        //shopItems.add(new ShopItem("萝卜",R.drawable.a2,111.6));//使用notifyItemInserted方法向末尾处添加item,notifyItemInserted(getItemCount());
                        //其中getItemCount()才能正确的计算出插入的位置,使用list.size()-1计算插入位置，一个一个的插入
                        //MyRecyclerViewAdapter.this.notifyItemInserted(shopItems.size());*/
                        intent=new Intent(MainActivity.this,InputActivity.class);
                        intent.putExtra("position",position);
                        MainActivity.this.startActivityForResult(intent, REQUEST_CODE_ADD);
                        //MainActivity.this.finish();
                        break;
                    case 2:
                        intent=new Intent(MainActivity.this,InputActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("name",shopItems.get(position).getName());
                        intent.putExtra("price",shopItems.get(position).getPrice());
                        MainActivity.this.startActivityForResult(intent, REQUEST_CODE_EDIT);
                        break;
                    case 3:
                      AlertDialog.Builder alertDB = new AlertDialog.Builder(MainActivity.this);
                        alertDB.setPositiveButton(MainActivity.this.getResources().getString(R.string.string_confirmation), new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                shopItems.remove(position);
                                dataBank.saveData();
                                MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                            }
                        });
                        alertDB.setNegativeButton(MainActivity.this.getResources().getString(R.string.string_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                        alertDB.setMessage(MainActivity.this.getResources().getString(R.string.string_confirm_delete) +shopItems.get(position).getName()+"？");
                        alertDB.setTitle(MainActivity.this.getResources().getString(R.string.hint)).show();
                        break;

                }

                return false;
            }
        }
    }
}

 